package com.tongcao.cn.contoller;

import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.google.common.collect.Maps;
import com.tongcao.cn.configcenter.nacos.NacosExampleBean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.alibaba.nacos.api.common.Constants.DEFAULT_GROUP;
import static org.springframework.web.bind.annotation.RequestMethod.GET;

/**
 * @author:tongcao
 * @since:2019/7/24 18:22
 * Description:ncaos 配置中心测试
 */
@Controller
@RequestMapping("/config")
public class NacosController {

    @NacosValue(value = "${useLocalCache:false}", autoRefreshed = true)
    private boolean useLocalCache;

    @NacosValue(value = "${userName:tongcao}", autoRefreshed = true)
    private String userName;

    @NacosValue(value = "${user.github:}", autoRefreshed = true)
    private String userGithup;

    public static final String DATA_ID = "properties-data-id";

    @NacosInjected
    private ConfigService configService;

    @NacosInjected
    private NamingService namingService;

    @Resource
    private NacosExampleBean nacosExampleBean;

    /**
     * 启动配置管理
     *
     * @return
     */
    @RequestMapping(value = "/get", method = GET)
    @ResponseBody
    public Map<String, String> get() {
        final HashMap<String, String> map = Maps.newHashMap();
        map.put("cache", String.valueOf(useLocalCache));
        map.put("username", userName);
        return map;
    }

    @RequestMapping(value = "/getConf", method = GET)
    @ResponseBody
    public String getConfig() throws Exception {
        final String config = configService.getConfig(DATA_ID, DEFAULT_GROUP, 300);
        return config;
    }


    @RequestMapping(value = "/getexp", method = GET)
    @ResponseBody
    public Map<String, String> getExample() {
        final HashMap<String, String> map = Maps.newHashMap();
        map.put("url", nacosExampleBean.getUserUrl());
        map.put("username", nacosExampleBean.getUserName());
        return map;
    }

    /**
     * Nacos 启动服务发现
     *
     * @param serviceName
     * @return
     * @throws NacosException
     */
    @RequestMapping(value = "/list", method = GET)
    @ResponseBody
    public List<Instance> list(@RequestParam String serviceName) throws NacosException {
        return namingService.getAllInstances(serviceName);
    }
}
